import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import baseUrl from '@/utils/baseUrl'
import router from '../router'

// 创建axios实例
const service = axios.create({
  baseURL: baseUrl,
  timeout: 30000
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Auth'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    const res = error.response
    console.log(res)
    Message({
      message: res.data.msg || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
    switch (res.status) {
      // 返回 401 清除token信息并跳转到登录页面
      case 401:
        removeToken()
        store.commit('user/SET_TOKEN', '')
        localStorage.removeItem('USER_INFO')
        router.replace({
          path: '/login'
        })
        break
    }
    return Promise.reject(error)
  }
)

export default service
